﻿using MQTTnet.Client;
using MQTTnet;
using NAudio.Wave;
using QServices;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace QQPlcPlayer
{
	public   class AlarmHelper
	{
		public  Task? AlarmTask { get; set; }
		public  bool IsStop { get; set; }
		public  object lockobj = new object();
		public DateTime LastAlarmTime { get; set; }
		public  void StopAlarm()
		{
			IsStop = true;
		}

		public AlarmHelper(string path)
		{
			VideoPath = path;
		}


		public string VideoPath {  get; set; }
		
		public  void StartAlarm()
		{

			Task.Run(async () =>
			{
				if (AppRuntime.IsNetworkAvailable() && AppRuntime.m_mqttclient != null)
				{
					var AudioType = "weiliao";
					if (VideoPath.Contains("充电")) AudioType = "chongdian";
					else if (VideoPath.Contains("喂料")) AudioType = "weiliao";
					else if (VideoPath.Contains("加料")) AudioType = "error";
					var CarNumber = AppRuntime.CarNumber;
					var obj = new { AudioType, CarNumber };
					var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(obj));
					var message = new MqttApplicationMessage
					{
						PayloadSegment = bytes,
						Topic = "PlayAudio",
						QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce
					};

					if (!AppRuntime.m_mqttclient.IsConnected) await AppRuntime.m_mqttclient.ReconnectAsync();
					await AppRuntime.m_mqttclient.PublishAsync(message);
				}



			});
			
			lock (lockobj)
			{
				if (AlarmTask != null && AlarmTask.Status == TaskStatus.Running) return;
				if (string.IsNullOrWhiteSpace(VideoPath)) return;
				if (IsStop) return;
				IsStop = false;
				AlarmTask = Task.Run(() =>
				{
					LastAlarmTime = DateTime.Now;
					while (true)
					{

						using var audioFile = new AudioFileReader(VideoPath);

						using var outputDevice = new WaveOutEvent();
						outputDevice.Init(audioFile);
						outputDevice.Volume = 1.0f;						
						outputDevice.Play();
						while (outputDevice.PlaybackState == PlaybackState.Playing)
						{
							if (IsStop) break;
							Thread.Sleep(1000);
							var timespan=(DateTime.Now- LastAlarmTime).TotalSeconds;
							if(timespan > 9000)
							{
								StopAlarm();
							}
						}
						Thread.Sleep(1000);
						if (IsStop) break;
					}
				});
			}
		}

		
	}
}
